package org.zfes.snowier.zbss.xzy.biz.vedio.service.impl;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.text.translate.NumericEntityUnescaper.OPTION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.core.util.encypt.HexUtil;
import org.zfes.snowier.core.util.encypt.MD5Util;
import org.zfes.snowier.core.util.AppCtxUtil;
import org.zfes.snowier.core.util.FileUtil;
import org.zfes.snowier.core.util.UUIDUtil;
import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.core.data.ParamMap;
import com.google.common.collect.Lists;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;

import org.zfes.snowier.core.data.SelectVo;

import org.zfes.snowier.zbss.xzy.biz.vedio.service.ICloudVedioService;
import org.zfes.snowier.zbss.xzy.tvedio.CloudCoverCreateDto;
import org.zfes.snowier.zbss.xzy.tvedio.CloudVedioCreateDto;
import org.zfes.snowier.zbss.xzy.biz.vedio.dao.CloudVedioMapper;
import org.zfes.snowier.zbss.xzy.biz.vedio.model.CloudImage;
import org.zfes.snowier.zbss.xzy.biz.vedio.model.CloudVedio;
import java.util.stream.Stream;
@Service
public class CloudVedioServiceImpl implements ICloudVedioService{
	
	private Logger logger =LoggerFactory.getLogger(this.getClass());
 	@Autowired
	private CloudVedioMapper cloudVedioMapper;
	
	@Value("${localFilePath:}")
	private String localFilePath="D\\50d3b2fc-ec2b-11ea-acfd-5ab503a75443.mp4";
	
	@Value("${tencentVodSecretId:AKIDHD8pGQwOAm8E6jeE4gCSSDl24i8JNsHR}")
	private String secretId="AKIDHD8pGQwOAm8E6jeE4gCSSDl24i8JNsHR";
	
	@Value("${tencentVodSecretKey:2pPxGDxkJdi3A0b1RfmhMn21kKerpYLs}")
	private String secretKey="2pPxGDxkJdi3A0b1RfmhMn21kKerpYLs";
	
	@Value("${antiLeechKey:HwtPo9C4a0Lyqig8dLrH}")
	private String antiLeechKey="HwtPo9C4a0Lyqig8dLrH";
	
	ICloudVedioService self;
	
	private VodUploadClient client =null;
	private VodUploadClient getClient() {
		if(client==null) {
			client= new VodUploadClient(secretId, secretKey);
		}
		return client;
	}
 	public ICloudVedioService getSelf() {
 		if(self==null) {
 			self=AppCtxUtil.cfg.getBean(ICloudVedioService.class);
 		}
		return self;
	}

 	
 	@Transactional(rollbackFor=Exception.class)
 	@Override
	public  Long uploadMsgVedio(CloudVedioCreateDto cloudVedioDto) {
 		ZBeanUtil.validateBean(cloudVedioDto);
 		
 		CloudVedio cloudVedio = new CloudVedio()
 				.setDeviceNum(cloudVedioDto.getDeviceNum())
 				.setMessageId(cloudVedioDto.getMessageId())
 				.setLocalVedioFilePath(cloudVedioDto.getVedioFilePath())
 				.setLocalCoverFilePath(cloudVedioDto.getCoverFilePath());
 		
 		Long vid=createCloudVedio(cloudVedio);
 		cloudVedio.setId(vid);
 		
 		getSelf().uploadCloud(cloudVedio);
 		
		return cloudVedio.getId();
 	}
 	@Async
 	@Override
 	public  void uploadCloud(CloudVedio cloudVedio) {
 		 try {
	 			 String videoFilePath = cloudVedio.getLocalVedioFilePath();
	 			 String coverFilePath =	cloudVedio.getLocalCoverFilePath();
	 			 
	 			 VodUploadResponse response = getClient().upload("ap-guangzhou", new VodUploadRequest(videoFilePath,coverFilePath));
	 			 
	 			CloudVedio  updater = new CloudVedio(cloudVedio.getId())
		 					.setMediaUrl(response.getMediaUrl())
		 					.setCoverUrl(response.getCoverUrl())
		 					.setRequestId(response.getRequestId())
		 					.setVedioFileId(response.getFileId())
		 					.setUploadStatus(Byte.valueOf("1"));
	 			
	 	 		updateCloudVedio(updater);
	 	 		
	 	 		//FileUtil.deleteFile( videoFilePath);
	 	 		//FileUtil.deleteFile( coverFilePath);
	 	 		
	 	 		logger.info("Upload FileId = {}", updater);
 		 } catch (Exception e) {
 				CloudVedio  updater = new CloudVedio(cloudVedio.getId()).setUploadStatus(Byte.valueOf("0"));
 				updateCloudVedio(updater);
 				logger.error("Upload Err", e);
 		}
  }
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<CloudVedio> loaByMessageId(Long messageId,Byte status){
		if(messageId!=null){
			List<CloudVedio> vedios= cloudVedioMapper.selectByMessageId( messageId,status);
			if(vedios!=null) {
				vedios.forEach(v->{
					v.setMediaUrl(parseMediaUrl(v).orElse(""));
				});
				
			}
			
			return cloudVedioMapper.selectByMessageId( messageId,status);
		}
		return Lists.newArrayList();
	}
 	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<String> loadMsgVedioUrl(Long vedioId){
 		Optional<CloudVedio> vedioOP =loadCloudVedioById(vedioId);
		if(!vedioOP.isPresent()) {
			return Optional.empty();
		}
	  
	  return parseMediaUrl(vedioOP.get());
	  
	}
 	
 	private Optional<String> parseMediaUrl(CloudVedio vedio){
 		//sign = md5(KEY + Dir + t + exper + rlimit + us)
		//http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/4fc6ed8b5285890811314382837/f0.mp4
		//http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/4fc87d865285890811314385343/f0.mp4?t=5fde3a4c&sign=3ba724505de50773bd9b95483c08174c
		//http://example.vod2.myqcloud.com/dir1/dir2/myVideo.mp4?
		//t=5a71afc0&exper=300&us=72d4cd1101&sign=547d98c4b91e81b5ea55c95cef63223f0
	  String mediaUrl =vedio.getMediaUrl();//"http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/4fc6ed8b5285890811314382837/f0.mp4";// vedioOP.get().getMediaUrl();
		  String dirS=ZStrUtil.substringAfter(mediaUrl, "myqcloud.com");
		   dirS=ZStrUtil.substringBeforeLast(dirS, "/");
		   dirS+="/";
		   
		 String signParam="";
		  Long t=new Date(new Date().getTime() + 1000 * 60).getTime();//过期时间戳1517400000的十六进制表示结果
		String appkey="HwtPo9C4a0Lyqig8dLrH";
		 String hexTime =Long.toHexString(t);
		 String us=UUIDUtil.fastUUID();//生成的随机字符串
		 signParam=signParam+"t="+hexTime+"&us="+us;
		 String trv=appkey+dirS+hexTime+us;
		  String sign =MD5Util.stringToMD5(trv); //生成的随机字符串
		  String playUrl = mediaUrl+"?"+signParam+"&sign="+sign;
	  
	  return Optional.ofNullable(playUrl);
 	}
 	

 
	@Transactional(rollbackFor=Exception.class)
 	@Override
	public Long createCloudVedio(CloudVedio cloudVedio) {
		ZBeanUtil.setCreateInfo(cloudVedio);
		ZBeanUtil.validateBean(cloudVedio);
		cloudVedioMapper.insertSelective(cloudVedio);
		return cloudVedio.getId();
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<CloudVedio> loadCloudVedioById(Long id) {
		if(id!=null){
			return Optional.ofNullable(cloudVedioMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
		
	}

	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateCloudVedio(CloudVedio cloudVedio) {
		ZBeanUtil.setUpdatedInfo(cloudVedio);
		cloudVedioMapper.updateByPrimaryKeySelective(cloudVedio);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteCloudVedio(Long id) {
		ZAssert.notNull(id, "请选择要操作的数据");
		cloudVedioMapper.deleteByPrimaryKey(id);
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setCloudVedioStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {-1,0,1}).anyMatch(val->val.equals(status))) {
			ZAlert.serviceLogicalError("状态参数错误");
		}
		cloudVedioMapper.updateStatus( id,  status) ;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadCloudVedioDataSet(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		DataSet ds=DataSet.newDS2(cloudVedioMapper.selectListCount(pm), cloudVedioMapper.selectMapListPage(pm));
		return ds;
	}
	
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<SelectVo> loadCloudVedioSelectVo(String keywords) {
		if(ZStrUtil.hasText(keywords)) {
			
		}
		List<SelectVo> voList=cloudVedioMapper.selectDropList(Byte.valueOf("1"));
		
		return voList==null?Lists.newArrayList():voList;
	}
// 	public static void main(String[] args) {
//		
//		  String mediaUrlx ="http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/4fc6ed8b5285890811314382837/f0.mp4";// vedioOP.get().getMediaUrl();
//		  String dirS=ZStrUtil.substringAfter(mediaUrlx, "myqcloud.com");
//		   dirS=ZStrUtil.substringBeforeLast(dirS, "/");
//		   dirS+="/";
//		   System.out.println(dirS);
//		   
//		 String signParam="";
//		 String mediaUrl = "http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/4fc6ed8b5285890811314382837/f0.mp4";
//		  String dir="/beab3ec2vodcq1304320487/4fc6ed8b5285890811314382837/";
//		  Long t=new Date(new Date().getTime() + 1000 * 60).getTime();//过期时间戳1517400000的十六进制表示结果
//		
//		 String hexTime =Long.toHexString(t);
//		 String us="456s4das5dsddsaf0";//UUIDUtil.fastUUID();//生成的随机字符串
//		 signParam=signParam+"t="+hexTime+"&us="+us;
//		 String trv="HwtPo9C4a0Lyqig8dLrH"+dir+hexTime+us;
//		 System.out.println(trv);
//		  String sign =MD5Util.stringToMD5(trv); //生成的随机字符串
//		  String playUrl=mediaUrl+"?"+signParam+"&sign="+sign;
//		  System.out.println(playUrl);
//}
}